#include "mainwindow.h"
#include "traitmatchgamepage.h" 
#include "whichscenariogamepage.h" 
#include <QApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QDebug>
#include <QJsonParseError>
#include <QDir>
#include <QScrollArea>
#include <QPixmap>
#include <QTextEdit>

// MainWindow Implementation
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      questionnairePage(nullptr), // Initialize pointers
      traitMatchGamePage(nullptr),
      whichScenarioGamePage(nullptr)
{
    QString appPath = QCoreApplication::applicationDirPath();
    dataPath = QDir(appPath).filePath("data"); 

    loadMBTIQuestions(); 
    loadMBTIDatabase();  
    setupUi();
}

MainWindow::~MainWindow()
{
    // Qt handles child widget deletion if they are parented correctly
}

void MainWindow::setupUi()
{
    stackedWidget = new QStackedWidget(this);

    welcomePage = new WelcomePage(this);
    connect(welcomePage->startButton, &QPushButton::clicked, this, &MainWindow::startTest);
    connect(welcomePage->traitMatchGameButton, &QPushButton::clicked, this, &MainWindow::showTraitMatchGame);
    connect(welcomePage->whichScenarioGameButton, &QPushButton::clicked, this, &MainWindow::showWhichScenarioGame);
    stackedWidget->addWidget(welcomePage);

    // questionnairePage is created on demand in startTest()

    resultsPage = new ResultsPage(this);
    connect(resultsPage->restartButton, &QPushButton::clicked, this, &MainWindow::showWelcomePage); // Changed to showWelcomePage for consistency
    stackedWidget->addWidget(resultsPage);

    traitMatchGamePage = new TraitMatchGamePage(this);
    QPushButton* traitMatchBackButton = traitMatchGamePage->findChild<QPushButton*>("GameBackButton");
    if(traitMatchBackButton) {
        connect(traitMatchBackButton, &QPushButton::clicked, this, &MainWindow::showWelcomePage);
    } else {
        qWarning() << "TraitMatchGamePage back button (GameBackButton) not found!";
    }
    stackedWidget->addWidget(traitMatchGamePage);

    whichScenarioGamePage = new WhichScenarioGamePage(this);
    QPushButton* scenarioGameBackButton = whichScenarioGamePage->findChild<QPushButton*>("GameBackButton");
    if(scenarioGameBackButton) {
        connect(scenarioGameBackButton, &QPushButton::clicked, this, &MainWindow::showWelcomePage);
    } else {
        qWarning() << "WhichScenarioGamePage back button (GameBackButton) not found!";
    }
    stackedWidget->addWidget(whichScenarioGamePage);

    setCentralWidget(stackedWidget);
    stackedWidget->setCurrentWidget(welcomePage);
    resize(850, 750); 
    setWindowTitle("MBTI 性格探索与趣味游戏");
}

void MainWindow::loadMBTIQuestions() {
    QString questionsFilePath = QDir(dataPath).filePath("parsed_questions_v4_corrected.json");
    QFile file(questionsFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", QString("无法打开MBTI问卷文件，请确保 \"data/parsed_questions_v4_corrected.json\" 文件存在于程序目录下。路径: %1").arg(questionsFilePath));
        qCritical() << "Failed to open MBTI questions file: " << questionsFilePath;
        return;
    }
    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        QMessageBox::critical(this, "错误", "解析MBTI问卷JSON失败: " + parseError.errorString());
        qCritical() << "Failed to parse MBTI questions JSON: " << parseError.errorString();
        return;
    }

    if (!doc.isArray()) {
        QMessageBox::critical(this, "错误", "MBTI问卷JSON格式不是一个数组。");
        qCritical() << "MBTI questions JSON is not an array.";
        return;
    }

    QJsonArray questionsArray = doc.array();
    questionsList.clear(); 
    for (const QJsonValue &value : questionsArray) {
        QJsonObject obj = value.toObject();
        MBTIQuestion q;
        q.id = obj["id"].toInt();
        q.text = obj["text"].toString();
        q.option_a_text = obj["option_a_text"].toString();
        q.option_b_text = obj["option_b_text"].toString();
        q.option_a_scores_pole = obj["option_a_scores_pole"].toString().trimmed().toUpper();
        q.option_b_scores_pole = obj["option_b_scores_pole"].toString().trimmed().toUpper();
        questionsList.append(q);
    }
    qInfo() << "MBTI questions loaded. Total questions: " << questionsList.size();
    if (questionsList.size() != 93) {
        QMessageBox::warning(this, "问卷数量不匹配", QString("加载了 %1 道题目，但预期是 93 道。请检查JSON文件。").arg(questionsList.size()));
    }
}

void MainWindow::loadMBTIDatabase() {
    QString dbFilePath = QDir(dataPath).filePath("mbti_database.json");
    QFile file(dbFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", QString("无法打开MBTI数据库文件，请确保 \"data/mbti_database.json\" 文件存在于程序目录下。路径: %1").arg(dbFilePath));
        qCritical() << "Failed to open MBTI database file: " << dbFilePath;
        return;
    }
    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        QMessageBox::critical(this, "错误", "解析MBTI数据库JSON失败: " + parseError.errorString());
        qCritical() << "Failed to parse MBTI database JSON: " << parseError.errorString();
        return;
    }
    if (doc.isArray()) {
        mbtiDatabase = doc.array();
        qInfo() << "MBTI database loaded successfully with " << mbtiDatabase.size() << " types.";
    } else {
        QMessageBox::critical(this, "错误", "MBTI数据库JSON格式不是一个数组。");
        qCritical() << "MBTI database JSON is not an array.";
    }
}

void MainWindow::startTest()
{
    if (!questionsList.isEmpty()) {
        if (questionnairePage) { 
            stackedWidget->removeWidget(questionnairePage);
            delete questionnairePage;
            questionnairePage = nullptr; // Important: set to null after delete
        }
        questionnairePage = new QuestionnairePage(questionsList, this);
        connect(questionnairePage, &QuestionnairePage::testSubmitted, this, &MainWindow::submitTest);
        stackedWidget->insertWidget(1, questionnairePage); // Insert at a specific index if needed
        stackedWidget->setCurrentWidget(questionnairePage);
    } else {
        QMessageBox::warning(this, "没有题目", "MBTI问卷未能加载，请检查数据文件。");
    }
}

void MainWindow::submitTest(const QVector<int>& answers)
{
    QString mbtiType = calculateMBTI(answers);
    QJsonObject details = getMBTIDetails(mbtiType);
    
    QPixmap avatarPixmap;
    QString avatarPath = QDir(QCoreApplication::applicationDirPath()).filePath(QString("mbti_avatars/%1.png").arg(mbtiType));
    qDebug() << "Attempting to load avatar from: " << avatarPath;
    if (QFile::exists(avatarPath)) {
        qDebug() << "Avatar file exists at path: " << avatarPath;
        bool loaded = avatarPixmap.load(avatarPath);
        if (loaded) {
            qDebug() << "Avatar loaded successfully for" << mbtiType;
            if (avatarPixmap.isNull()) {
                qWarning() << "Avatar for" << mbtiType << "is null after successful load reported!";
                QMessageBox::warning(this, "图片加载警告", QString("尝试加载头像'%1'时，文件声称加载成功但图片内容为空。路径: %2").arg(mbtiType).arg(avatarPath));
            }
        } else {
            qWarning() << "Failed to load avatar for" << mbtiType << "from" << avatarPath << " even though file exists. Pixmap error: " << avatarPixmap.isNull();
            QMessageBox::critical(this, "图片加载失败", QString("无法加载头像'%1'，即使文件存在。请检查文件格式或权限。路径: %2").arg(mbtiType).arg(avatarPath));
        }
    } else {
        qWarning() << "Avatar file NOT found for" << mbtiType << "at" << avatarPath;
        QMessageBox::critical(this, "图片文件缺失", QString("图片文件缺失：找不到头像文件 '%1.png'。\n\n请确保满足以下条件：\n1. 程序可执行文件 (例如 MBTI_Qt_App.exe) 所在的目录中。\n2. 该目录下有一个名为 'mbti_avatars' 的子文件夹。\n3. 'mbti_avatars' 文件夹中包含名为 '%1.png' 的图片文件。\n\n程序尝试加载的完整路径是：%2").arg(mbtiType).arg(avatarPath));
    }

    resultsPage->setResult(mbtiType, details, avatarPixmap);
    stackedWidget->setCurrentWidget(resultsPage);
}

void MainWindow::restartTest() // This is called by ResultsPage restart button
{
    stackedWidget->setCurrentWidget(welcomePage);
}

QString MainWindow::calculateMBTI(const QVector<int>& answers)
{
    if (answers.size() != questionsList.size()) {
        qWarning() << "Answer count (" << answers.size() << ") does not match question count (" << questionsList.size() << ").";
        QMessageBox::critical(this, "计分错误", "答案数量不匹配，无法计算结果。");
        return "XXXX"; 
    }
    QMap<QString, int> scores;
    scores["E"] = 0; scores["I"] = 0; scores["S"] = 0; scores["N"] = 0;
    scores["T"] = 0; scores["F"] = 0; scores["J"] = 0; scores["P"] = 0;
    for (int i = 0; i < questionsList.size(); ++i) {
        const MBTIQuestion& q = questionsList[i];
        int answer = answers[i]; 
        if (answer == 0) { 
            if (!q.option_a_scores_pole.isEmpty() && scores.contains(q.option_a_scores_pole)) scores[q.option_a_scores_pole]++;
            else qWarning() << "Invalid or empty scoring pole for Q" << q.id << " Option A:" << q.option_a_scores_pole;
        } else if (answer == 1) { 
            if (!q.option_b_scores_pole.isEmpty() && scores.contains(q.option_b_scores_pole)) scores[q.option_b_scores_pole]++;
            else qWarning() << "Invalid or empty scoring pole for Q" << q.id << " Option B:" << q.option_b_scores_pole;
        } 
    }
    QString resultType = "";
    resultType += (scores["E"] >= scores["I"]) ? "E" : "I";
    resultType += (scores["S"] >= scores["N"]) ? "S" : "N";
    resultType += (scores["T"] >= scores["F"]) ? "T" : "F";
    resultType += (scores["J"] >= scores["P"]) ? "J" : "P";
    qDebug() << "MBTI Scores: E:" << scores["E"] << "I:" << scores["I"] << "S:" << scores["S"] << "N:" << scores["N"] << "T:" << scores["T"] << "F:" << scores["F"] << "J:" << scores["J"] << "P:" << scores["P"];
    qDebug() << "Calculated Type:" << resultType;
    return resultType;
}

QJsonObject MainWindow::getMBTIDetails(const QString& mbtiType)
{
    for (const QJsonValue &value : mbtiDatabase) {
        QJsonObject obj = value.toObject();
        if (obj["type"].toString() == mbtiType) return obj;
    }
    qWarning() << "MBTI type details not found for: " << mbtiType;
    QJsonObject errorObj; errorObj["type"] = mbtiType; errorObj["title"] = "未知类型";
    errorObj["description"] = "数据库中未找到此MBTI类型的详细信息。";
    return errorObj; 
}

// New slots implementation for game navigation
void MainWindow::showTraitMatchGame()
{
    if (traitMatchGamePage) {
        // traitMatchGamePage->resetGame(); // Call reset if you want the game to start fresh
        stackedWidget->setCurrentWidget(traitMatchGamePage);
    }
}

void MainWindow::showWhichScenarioGame()
{
    if (whichScenarioGamePage) {
        // whichScenarioGamePage->startGame(); // Call start if you want the game to start fresh
        stackedWidget->setCurrentWidget(whichScenarioGamePage);
    }
}

void MainWindow::showWelcomePage()
{
    stackedWidget->setCurrentWidget(welcomePage);
}


// WelcomePage Implementation
WelcomePage::WelcomePage(QWidget *parent) : QWidget(parent)
{
    setObjectName("WelcomePageWidget");
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(50, 50, 50, 50);
    layout->setSpacing(20);

    titleLabel = new QLabel("MBTI 性格探索之旅", this);
    titleLabel->setObjectName("WelcomeTitleLabel"); 
    titleLabel->setStyleSheet("font-size: 32pt; font-weight: bold; color: #FF4500; qproperty-alignment: AlignCenter;");

    introLabel = new QLabel("准备好发现隐藏的自己了吗？\n进行专业的MBTI性格测试，或体验有趣的性格小游戏！", this);
    introLabel->setObjectName("WelcomeIntroLabel");
    introLabel->setStyleSheet("font-size: 16pt; color: #555555; qproperty-alignment: AlignCenter; line-height: 1.5;");
    introLabel->setWordWrap(true);

    startButton = new QPushButton("🚀 开始MBTI测试", this);
    startButton->setObjectName("StartButton"); 
    startButton->setMinimumHeight(50);
    startButton->setIconSize(QSize(32,32));

    traitMatchGameButton = new QPushButton("🎮 性格标签连连看", this);
    traitMatchGameButton->setObjectName("GameButton");
    traitMatchGameButton->setMinimumHeight(45);

    whichScenarioGameButton = new QPushButton("🎲 我是哪一型？小挑战", this);
    whichScenarioGameButton->setObjectName("GameButton");
    whichScenarioGameButton->setMinimumHeight(45);

    layout->addStretch(1);
    layout->addWidget(titleLabel);
    layout->addWidget(introLabel);
    layout->addSpacing(30);
    layout->addWidget(startButton, 0, Qt::AlignHCenter);
    layout->addSpacing(15);
    layout->addWidget(traitMatchGameButton, 0, Qt::AlignHCenter);
    layout->addSpacing(10);
    layout->addWidget(whichScenarioGameButton, 0, Qt::AlignHCenter);
    layout->addStretch(2);
    setLayout(layout);
}

// QuestionnairePage Implementation
QuestionnairePage::QuestionnairePage(const QVector<MainWindow::MBTIQuestion>& questions, QWidget *parent)
    : QWidget(parent), questionsData(questions)
{
    setObjectName("QuestionnairePageWidget"); 
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15);

    QHBoxLayout *progressLayout = new QHBoxLayout();
    progressBar = new QProgressBar(this);
    progressBar->setRange(0, questionsData.size());
    progressBar->setValue(0);
    progressBar->setTextVisible(false);
    progressBar->setFixedHeight(25);
    progressBar->setStyleSheet("QProgressBar { border: 2px solid #FFA07A; border-radius: 10px; background-color: #FFF0F5; text-align: center; } QProgressBar::chunk { background-color: #FF7F50; border-radius: 8px; }");
    
    progressLabel = new QLabel("进度: 0% (0/93)", this);
    progressLabel->setStyleSheet("font-size: 12pt; font-weight: bold; color: #CD5C5C;");

    progressLayout->addWidget(progressBar, 1);
    progressLayout->addWidget(progressLabel, 0, Qt::AlignRight);
    mainLayout->addLayout(progressLayout);

    scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setObjectName("QuestionScrollArea");
    
    QWidget *questionsContainerWidget = new QWidget();
    questionsContainerWidget->setObjectName("QuestionsContainer");
    questionsLayout = new QVBoxLayout(questionsContainerWidget);
    questionsLayout->setSpacing(20);
    questionsLayout->setContentsMargins(10,10,10,20);
    questionsContainerWidget->setLayout(questionsLayout);

    answerGroups.clear(); 
    for (int i = 0; i < questionsData.size(); ++i) {
        const auto& q_data = questionsData[i];
        QGroupBox *groupBox = new QGroupBox(QString("第 %1 题 / 共 %2 题").arg(i + 1).arg(questionsData.size()));
        groupBox->setObjectName("QuestionGroupBox");
        QVBoxLayout *groupLayout = new QVBoxLayout(groupBox);
        groupLayout->setSpacing(10);
        
        QLabel *questionTextLabel = new QLabel(q_data.text, groupBox); // Renamed to avoid conflict
        questionTextLabel->setWordWrap(true);
        questionTextLabel->setStyleSheet("font-size: 14pt; color: #333; margin-bottom: 5px;");
        groupLayout->addWidget(questionTextLabel);

        QRadioButton *optionA = new QRadioButton(QString(" %1").arg(q_data.option_a_text), groupBox);
        QRadioButton *optionB = new QRadioButton(QString(" %1").arg(q_data.option_b_text), groupBox);
        optionA->setObjectName("OptionRadioButton");
        optionB->setObjectName("OptionRadioButton");
        
        QButtonGroup *buttonGroup = new QButtonGroup(this);
        buttonGroup->addButton(optionA, 0); 
        buttonGroup->addButton(optionB, 1); 
        connect(buttonGroup, qOverload<QAbstractButton*, bool>(&QButtonGroup::buttonToggled), this, &QuestionnairePage::updateProgress);
        answerGroups.append(buttonGroup);

        QVBoxLayout *optionsVBLayout = new QVBoxLayout();
        optionsVBLayout->addWidget(optionA);
        optionsVBLayout->addWidget(optionB);
        optionsVBLayout->setSpacing(8);
        groupLayout->addLayout(optionsVBLayout);
        questionsLayout->addWidget(groupBox);
    }

    scrollArea->setWidget(questionsContainerWidget);
    mainLayout->addWidget(scrollArea, 1);

    submitButton = new QPushButton("✨ 完成！查看结果 ✨", this);
    submitButton->setObjectName("SubmitButton"); 
    submitButton->setMinimumHeight(50);
    connect(submitButton, &QPushButton::clicked, this, &QuestionnairePage::handleSubmit);
    mainLayout->addWidget(submitButton, 0, Qt::AlignHCenter);
    setLayout(mainLayout);
    updateProgress();
}

void QuestionnairePage::updateProgress() {
    int answeredCount = 0;
    for (QButtonGroup* group : answerGroups) {
        if (group->checkedId() != -1) {
            answeredCount++;
        }
    }
    progressBar->setValue(answeredCount);
    double percentage = (questionsData.isEmpty() ? 0 : (static_cast<double>(answeredCount) / questionsData.size()) * 100);
    progressLabel->setText(QString("进度: %1% (%2/%3)").arg(static_cast<int>(percentage)).arg(answeredCount).arg(questionsData.size()));
}

QVector<int> QuestionnairePage::getAnswers()
{
    QVector<int> answers;
    for (QButtonGroup *group : answerGroups) {
        answers.append(group->checkedId());
    }
    return answers;
}

void QuestionnairePage::handleSubmit() {
    QVector<int> currentAnswers = getAnswers();
    for(int i=0; i < currentAnswers.size(); ++i) {
        if (currentAnswers[i] == -1) {
            QMessageBox msgBox(QMessageBox::Warning, "尚未完成", QString("请回答所有问题后再提交哦！\n\n第 <b>%1</b> 题还没有选择答案呢。").arg(i+1), QMessageBox::Ok, this);
            msgBox.setStyleSheet("QLabel{min-width: 300px; font-size: 12pt;} QPushButton{font-size: 10pt; padding: 8px 15px;}");
            msgBox.exec();
            if(questionsLayout->itemAt(i) && questionsLayout->itemAt(i)->widget()){
                scrollArea->ensureWidgetVisible(questionsLayout->itemAt(i)->widget());
            }
            return; 
        }
    }
    emit testSubmitted(currentAnswers);
}

// ResultsPage Implementation
ResultsPage::ResultsPage(QWidget *parent) : QWidget(parent)
{
    setObjectName("ResultsPageWidget"); 
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(10); // Adjusted spacing
    mainLayout->setContentsMargins(20, 20, 20, 20);

    resultTypeLabel = new QLabel("你的性格类型是：", this);
    resultTypeLabel->setObjectName("ResultTypeLabel"); 
    resultTypeLabel->setAlignment(Qt::AlignCenter);
    resultTypeLabel->setStyleSheet("font-size: 18pt; font-weight:bold; color: #333;");

    avatarLabel = new QLabel(this);
    avatarLabel->setObjectName("AvatarLabel");
    avatarLabel->setAlignment(Qt::AlignCenter);
    avatarLabel->setMinimumSize(150, 180);
    avatarLabel->setStyleSheet("border: 2px solid #FFD700; border-radius: 8px; background-color: #FFFFE0; margin-top: 5px; margin-bottom: 5px;");

    sloganLabel = new QLabel("口号：", this);
    sloganLabel->setObjectName("SloganLabel");
    sloganLabel->setStyleSheet("font-size: 14pt; font-style: italic; color: #D2691E; qproperty-alignment: AlignCenter; margin-bottom:10px;");
    sloganLabel->setWordWrap(true);

    QScrollArea *detailsScroll = new QScrollArea(this);
    detailsScroll->setWidgetResizable(true);
    detailsScroll->setObjectName("DetailsScrollArea");
    detailsScroll->setStyleSheet("QScrollArea { border: 1px solid #ddd; border-radius: 5px; } QWidget#DetailsContainerWidget { background-color: #fff; }");
    
    QWidget* detailsContainer = new QWidget();
    detailsContainer->setObjectName("DetailsContainerWidget");
    QVBoxLayout* detailsLayout = new QVBoxLayout(detailsContainer);
    detailsLayout->setSpacing(8);
    detailsLayout->setContentsMargins(15,15,15,15);
    detailsContainer->setLayout(detailsLayout);
    detailsScroll->setWidget(detailsContainer);

    detailsTextEdit = new QTextEdit(this);
    detailsTextEdit->setReadOnly(true);
    detailsTextEdit->setObjectName("DetailsTextEdit");
    detailsTextEdit->setStyleSheet("font-size:11pt; border: none; background-color: transparent;");

    strengthsTitleLabel = new QLabel("<b>闪光点:</b>", this);
    strengthsTitleLabel->setObjectName("SubTitleLabel");
    strengthsTextEdit = new QTextEdit(this);
    strengthsTextEdit->setReadOnly(true);
    strengthsTextEdit->setObjectName("StrengthsWeaknessesTextEdit");
    strengthsTextEdit->setFixedHeight(70);
    strengthsTextEdit->setStyleSheet("font-size:10pt; border: 1px solid #eee; border-radius: 4px; padding: 5px; background-color: #f9f9f9;");

    weaknessesTitleLabel = new QLabel("<b>可提升方面:</b>", this);
    weaknessesTitleLabel->setObjectName("SubTitleLabel");
    weaknessesTextEdit = new QTextEdit(this);
    weaknessesTextEdit->setReadOnly(true);
    weaknessesTextEdit->setObjectName("StrengthsWeaknessesTextEdit");
    weaknessesTextEdit->setFixedHeight(70);
    weaknessesTextEdit->setStyleSheet("font-size:10pt; border: 1px solid #eee; border-radius: 4px; padding: 5px; background-color: #f9f9f9;");

    celebritiesTitleLabel = new QLabel("<b>代表名人:</b>", this);
    celebritiesTitleLabel->setObjectName("SubTitleLabel");
    celebritiesTextEdit = new QTextEdit(this);
    celebritiesTextEdit->setReadOnly(true);
    celebritiesTextEdit->setObjectName("CelebritiesTextEdit");
    celebritiesTextEdit->setFixedHeight(70);
    celebritiesTextEdit->setStyleSheet("font-size:10pt; border: 1px solid #eee; border-radius: 4px; padding: 5px; background-color: #f9f9f9;");
    
    detailsLayout->addWidget(detailsTextEdit);
    detailsLayout->addWidget(strengthsTitleLabel);
    detailsLayout->addWidget(strengthsTextEdit);
    detailsLayout->addWidget(weaknessesTitleLabel);
    detailsLayout->addWidget(weaknessesTextEdit);
    detailsLayout->addWidget(celebritiesTitleLabel);
    detailsLayout->addWidget(celebritiesTextEdit);
    detailsLayout->addStretch();

    mainLayout->addWidget(resultTypeLabel);
    mainLayout->addWidget(avatarLabel, 0, Qt::AlignHCenter);
    mainLayout->addWidget(sloganLabel);
    mainLayout->addWidget(detailsScroll, 1);

    restartButton = new QPushButton("💖 再测一次 / 返回首页 💖", this);
    restartButton->setObjectName("RestartButton"); 
    restartButton->setMinimumHeight(50);
    mainLayout->addWidget(restartButton, 0, Qt::AlignHCenter);
    
    setLayout(mainLayout);
}

void ResultsPage::setResult(const QString& mbtiType, const QJsonObject& details, const QPixmap& avatarPixmap)
{
    resultTypeLabel->setText(QString("你的性格类型是：<br><span style='font-size:28pt; color:#DC143C;'>%1</span><br>(%2)")
                             .arg(mbtiType).arg(details["title"].toString("N/A")));
    
    if (!avatarPixmap.isNull()) {
        avatarLabel->setPixmap(avatarPixmap.scaled(140, 170, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    } else {
        avatarLabel->setText("未找到头像");
        avatarLabel->setPixmap(QPixmap());
    }

    sloganLabel->setText(QString("<i>%1</i>").arg(details["slogan"].toString("-")));

    QString descHtml = details["description"].toString("N/A").replace("\n", "<br>");
    QJsonArray fourLetters = details["four_letters"].toArray();
    if (!fourLetters.isEmpty()) {
        descHtml += "<br><br><b>四个维度解析：</b><br>";
        for (const QJsonValue &val : fourLetters) {
            QJsonObject letterObj = val.toObject();
            descHtml += QString(" - <b>%1</b> (%2): %3<br>")
                            .arg(letterObj["letter"].toString("N/A"))
                            .arg(letterObj["name"].toString("N/A"))
                            .arg(letterObj["description"].toString("N/A"));
        }
    }
    detailsTextEdit->setHtml(descHtml);

    QString strengthsStr = "";
    QJsonArray strengthsArray = details["strengths"].toArray();
    for(const QJsonValue& val : strengthsArray) { strengthsStr += "• " + val.toString() + "\n"; }
    strengthsTextEdit->setText(strengthsStr.replace("\n", "\n")); // Use \n for QTextEdit plain text

    QString weaknessesStr = "";
    QJsonArray weaknessesArray = details["weaknesses"].toArray();
    for(const QJsonValue& val : weaknessesArray) { weaknessesStr += "• " + val.toString() + "\n"; }
    weaknessesTextEdit->setText(weaknessesStr.replace("\n", "\n"));

    QString celebritiesStr = "";
    QJsonArray celebritiesArray = details["celebrities"].toArray();
    for(const QJsonValue& val : celebritiesArray) { celebritiesStr += val.toString() + ", "; }
    if (celebritiesStr.endsWith(", ")) celebritiesStr.chop(2);
    celebritiesTextEdit->setText(celebritiesStr.isEmpty() ? "暂无名人数据" : celebritiesStr);
}

